package com.atguigu.gulimall.ssoserver.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;

@Controller
public class LoginController {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userinfo")
    public String userInfo(@RequestParam("token") String token){
        String s = redisTemplate.opsForValue().get(token);
        return s;
    }

    @GetMapping("/login.html")
    public String loginPage(@CookieValue(value = "sso_token",required = false) String sso_token,
                            String redirectUrl, Model model){
        if (!StringUtils.isEmpty(sso_token)){
            return "redirect:"+redirectUrl+"?token="+sso_token;
        }
        model.addAttribute("url",redirectUrl);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(String username, String password, String redirectUrl, HttpServletResponse response){
        if ("zhangsan".equals(username)&&"123456".equals(password)){
            String token = UUID.randomUUID().toString().replace("-","");
            redisTemplate.opsForValue().set(token,username);
            Cookie ssoToken = new Cookie("sso_token",token);
            response.addCookie(ssoToken);
            return "redirect:"+redirectUrl+"?token="+token;
        }
        return "login";
    }

}
